import 'dart:io';

import 'package:jtsell_app/database/sql_string.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  final String _databaseName = "jtsell.db";
  final int _databaseVersion = 1;

  DatabaseHelper._internal();

  ///
  /// 操作数据库的DB对象
  ///
  Database _db;

  Future<Database> get db async {
    if (_db != null && _db.isOpen) {
      return _db;
    }
    _db = await _initDb();

    return _db;
  }

  static DatabaseHelper _instance;

  static Future<DatabaseHelper> getInstance() async {
    if (_instance == null) {
      _instance = DatabaseHelper._internal();
      _instance._db = await _instance._initDb();
    }

    return _instance;
  }

  ///
  /// 删除数据库
  ///
  Future<void> _deleteDb(String dbName) async {
    final String databasePath = await getDatabasesPath();
    // print(databasePath);
    final String path = join(databasePath, dbName);

    // make sure the folder exists
    if (await Directory(dirname(path)).exists()) {
      await deleteDatabase(path);
    }
  }

  ///
  /// 初始化数据库
  ///
  Future<Database> _initDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, _databaseName);
    print("database path is $path");
    Database ourDb = await openDatabase(path, version: _databaseVersion, onCreate: _onCreate);
    return ourDb;
  }

  //创建数据库表
  void _onCreate(Database db, int version) async {
    await db.execute(SqlString.CREATE_CART_TABLE);

    print("Table is created");
  }

  ///
  /// 插入对象
  ///
  Future<int> saveItem(String table, Map<String, dynamic> values) async {
    Database dbClient = await db;
    int res = await dbClient.insert(table, values);
    return res;
  }

  ///
  /// 查询所有数据
  ///
  Future<List<Map<String, dynamic>>> getTotalList(String tableName) async {
    Database dbClient = await db;
    List<Map<String, dynamic>> result = await dbClient.rawQuery("SELECT * FROM $tableName ");
    return result.toList();
  }

  ///
  /// 查询总数
  ///
  Future<int> getCount(String tableName) async {
    Database dbClient = await db;
    return Sqflite.firstIntValue(await dbClient.rawQuery("SELECT COUNT(1) FROM $tableName"));
  }

  ///
  /// 根据ID查询
  ///
  Future<Map<String, dynamic>> getItem(String tableName, int id) async {
    Database dbClient = await db;
    List<Map<String, dynamic>> result =
        await dbClient.rawQuery("SELECT * FROM $tableName WHERE id = $id");
    if (result.length == 0) {
      return null;
    }
    return result.first;
  }

  ///
  /// 清空数据
  ///
  Future<int> clear(String tableName) async {
    Database dbClient = await db;
    return await dbClient.delete(tableName);
  }

  ///
  /// 根据id删除
  ///
  Future<int> deleteItemByID(String tableName, String columnId, dynamic id) async {
    Database dbClient = await db;
    return await dbClient.delete(tableName, where: "$columnId = ?", whereArgs: [id]);
  }

  ///
  /// 修改
  ///
  Future<int> updateItem(String tableName, Map<String, dynamic> values,
      {String where, List<dynamic> whereArgs, ConflictAlgorithm conflictAlgorithm}) async {
    Database dbClient = await db;
    return await dbClient.update(tableName, values, where: where, whereArgs: whereArgs);
  }

  ///
  /// 关闭数据库
  ///
  Future<void> close() async {
    Database dbClient = await db;
    return dbClient.close();
  }
}
